www.gusucode.com > VC++ 实现批量附加MDF数据库-源码程序 > VC++ 实现批量附加MDF数据库-源码程序/code/AttachDlg.cpp

    // AttachDlg.cpp : implementation file
// Download by http://www.NewXing.com

#include "stdafx.h"
#include "Attach.h"
#include "AttachDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAttachDlg dialog

CAttachDlg::CAttachDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CAttachDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAttachDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CAttachDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAttachDlg)
	DDX_Control(pDX, IDC_LIST1, m_List);
	DDX_Control(pDX, IDC_EDIT1, m_Path);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAttachDlg, CDialog)
	//{{AFX_MSG_MAP(CAttachDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTSELECT, OnButselect)
	ON_BN_CLICKED(IDC_BUTATTACH, OnButattach)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAttachDlg message handlers

BOOL CAttachDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	m_List.SetExtendedStyle(LVS_EX_FLATSB					//扁平风格显示滚动条
		|LVS_EX_FULLROWSELECT							//允许整行选中
		|LVS_EX_HEADERDRAGDROP							//允许整列拖动
		|LVS_EX_ONECLICKACTIVATE						//单击选中项
		|LVS_EX_GRIDLINES);								//画出网格线
	m_List.InsertColumn(0,"原文件名",LVCFMT_LEFT,120,0);			//设置列名
	m_List.InsertColumn(1,"当前文件位置",LVCFMT_LEFT,240,1);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CAttachDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CAttachDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAttachDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CAttachDlg::OnButselect() 
{
	// TODO: Add your control notification handler code here
	CFileDialog file(true,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
		"MDF文件(*.MDF)|*.MDF| |",AfxGetMainWnd());				//构造打开对话框
	if (file.DoModal() == IDOK)									//单击确定按钮
	{
		CString strText = file.GetPathName();						//获得文件路径
		CString strName = file.GetFileName();						//获得文件名
		m_Path.SetWindowText(strText);							//显示文件路径
		m_StrName = strName.Left(strName.GetLength()-9);
		CString mdfname="",logname="";
		mdfname.Format("%s_Data.MDF",m_StrName);				//MDF文件路径
		logname.Format("%s_Log.LDF",m_StrName);				//LDF文件路径
		m_StrMdf = strText;
		m_StrLog = strText;
		m_StrLog.Replace("Data.MDF","Log.LDF");
		int n = m_List.GetItemCount();							//获得列表项目数
		m_List.InsertItem(n,"");								//插入行
		m_List.SetItemText(n,0,mdfname);						//插入列
		m_List.SetItemText(n,1,m_StrMdf);
		m_List.InsertItem(n+1,"");
		m_List.SetItemText(n+1,0,logname);
		m_List.SetItemText(n+1,1,m_StrLog);
	}
}

void CAttachDlg::OnButattach() 
{
	// TODO: Add your control notification handler code here
	for (int i=0;i<m_List.GetItemCount();i=i+2)						//获得列表中项目数
	{
		try
		{
			m_pConnection.CreateInstance("ADODB.Connection");  			//创建连接对象实例
			bstr_t strConnect="Provider=SQLOLEDB.1;Integrated Security=SSPI;\
				Persist Security Info=False;Initial Catalog=master;Data Source=.";
			m_pConnection->Open(strConnect,"","",adModeUnknown); 		//打开数据库
		}
		catch (_com_error e)											//捕捉错误
		{
			AfxMessageBox(e.Description()); 							//弹出错误
		}
		_bstr_t bstrSQL;
		bstrSQL = "select*from sysdatabases";						//设置查询语句
		CString strText;
		BOOL IsAttach = FALSE;
		m_pRecordset.CreateInstance(__uuidof(Recordset));		//初始化对象实例
		m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),
			adOpenDynamic,adLockOptimistic,adCmdText);			//打开记录集
		CString sql,strName,strMdf,strLog,name;
		strMdf  = m_List.GetItemText(i,1);						//获得MDF文件路径
		strLog  = m_List.GetItemText(i+1,1);						//获得LDF文件路径
		name    = m_List.GetItemText(i,0);						//获得文件名
		strName = name.Left(name.GetLength()-9);
		while(!m_pRecordset->adoEOF)
		{
			strText=(char*)(_bstr_t)m_pRecordset->GetCollect("name");
			if(strName == strText)								//判断数据库是否存在
			{
				IsAttach = TRUE;
			}
			m_pRecordset->MoveNext();
		}
		if(!IsAttach)
		{
			sql = "EXEC sp_attach_db @dbname = N'"+strName+"',@filename1 = N'"
				+strMdf+"', @filename2 = N'"+strLog+"'";			//设置附加语句
			m_pConnection->Execute((_bstr_t)sql,NULL,adCmdText);	//执行附加命令
		}
		else
			MessageBox(strName+"数据库已存在!");	
		m_pRecordset->Close();									//关闭记录集
		m_pConnection->Close();									//断开数据库连接
	}
	MessageBox("附加数据库完成!","附加数据库",MB_ICONASTERISK);
}